package com.spark.gaea.security.eis;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.crypto.hash.Sha512Hash;

import java.security.SecureRandom;

public class PasswordEncoder {
	public static final String DEFAULT_SALT = "SPARK_GAEA_DEFAULT_SALT_!)@$";
	public static final int DEFAULT_HASH_ITERATIONS = 1024;

	public static String encodePassword(final String password) {
		return encodePassword(password, "SPARK_GAEA_DEFAULT_SALT_!)@$", 1024);
	}

	public static String encodePassword(final String password, final String salt) {
		return encodePassword(password, salt, 1024);
	}

	public static String encodePassword(final String password, final String salt, final int hashIterations) {
		return new Sha512Hash(password, salt, hashIterations).toBase64();
	}

	public static String generatSalt(String salt) {
		if (StringUtils.isBlank(salt)) {
			salt = "SPARK_GAEA_DEFAULT_SALT_!)@$";
		}
		final SecureRandom sesssionKeyRandom = new SecureRandom();
		final byte[] sessionKeyBytes = new byte[20];
		sesssionKeyRandom.nextBytes(sessionKeyBytes);
		final String base64Random = Base64.encodeToString(sessionKeyBytes);
		return encodePassword(base64Random + salt);
	}
}
